import React from 'react'
import {Card, Button, Form, Input, Radio, Select, DatePicker, Modal, message, Tree} from 'antd'
import JustTable from "../../../components/JustTable";
import Utils from "../../../utils/utils";
import Axios from '../../../axios'
import moment from "../user";
import menuData from '../../../config/menuConfig'

const FormItem = Form.Item
const RadioGroup = Radio.Group
const TextArea = Input.TextArea
const Option = Select.Option
const TreeNode = Tree.TreeNode

export default class Permission extends React.Component {
    state = {
        itemList: [],
    }
    params = {
        page: 1
    }

    componentDidMount() {
        this.requestList()
    }

    requestList() {
        Axios.requestList(this, '/role/list', this.params, true)
    }

    handleOperate = (type) => {
        console.log(type)
        let item = this.state.selectedItem
        console.log(item)
        if (type == 'create') {
            this.setState({
                roleVisiable: true,
                title: '添加角色'
            })
        }
    }
    handleRoleSubmit = () => {
        console.log('handleModalSubmit')
        let rolInfo = this.roleForm.props.form.getFieldsValue()
        console.log(rolInfo)
        this.roleForm.props.form.validateFields((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
                Axios.ajax({
                    url: this.state.type = 'create' ? '/role/create' : '/city/open?edit',
                    data: rolInfo,
                    method: 'post'
                }).then((res) => {
                    console.log(res)
                    if (res.code == 0) {
                        message.success(res.msg)
                        this.roleForm.props.form.resetFields();
                        this.setState({
                            roleVisiable: false
                        })
                        this.requestList()
                    }
                })
            }
        });
    }
    handlePermission = () => {
        let item = this.state.selectedItem
        if (!item) {
            return Modal.info({
                title: '提示',
                content: '请选择数据',
            })
        }
        this.setState({
            isPermissionVisiable: true,
            roleInfo: item,
            menuInfo:item.menus
        })
    }
    handlePermissionSubmit = () => {
        //拼装提交的数据
        let roleData = this.permForm.props.form.getFieldsValue()
        roleData.role_id = this.state.selectedItem.id
        roleData.menus = this.state.menuInfo

        Axios.ajax({
            url: '/role/create',
            data: roleData,
            method: 'post'
        }).then((res) => {
            console.log(res)
            if (res.code == 0) {
                message.success(res.msg)
                this.permForm.props.form.resetFields();
                this.setState({
                    roleVisiable: false
                })
                this.requestList()
            }
        })
    }

    render() {
        const columns = [
            {
                title: '角色id',
                dataIndex: 'id',
            },
            {
                title: '角色名称',
                dataIndex: 'role_name',
            },
            {
                title: '创建时间',
                dataIndex: 'create_time',
                render: Utils.formatDate
            },
            {
                title: '状态',
                dataIndex: 'status',
                render:(value, row)=>{
                    return value==1?'开启':'关闭'
                }
            },
            {
                title: '授权时间',
                dataIndex: 'authorize_time',
                render: Utils.formatDate
            },
            {
                title: '授权人',
                dataIndex: 'authorize_user_name',
            },
        ]

        return (
            <div>
                <Card className={"operate-wrap"}>
                    <Button type={'primary'} onClick={() => {
                        this.handleOperate('create')
                    }}>创建</Button>
                    <Button type={'primary'} onClick={this.handlePermission}>设置权限</Button>
                    <Button type={'primary'}>用户授权</Button>
                </Card>
                <div className={"content-wrap"}>
                    <JustTable
                        columns={columns}
                        dataSource={this.state.itemList}
                        pagination={this.state.pagination}
                        // rowSelection = {'checkbox'}
                        rowSelection={'radio'}
                        selectedRowKeys={this.state.selectedRowKeys}
                        selectedItem={this.state.selectedItem}
                        selectedIds={this.state.selectedIds}
                        updateSelectedItem={Utils.updateSelectedItem.bind(this)}
                    />
                </div>
                <Modal
                    title={this.state.title}
                    visible={this.state.roleVisiable}
                    onOk={this.handleRoleSubmit}
                    onCancel={() => {
                        this.roleForm.props.form.resetFields();
                        this.setState({
                            roleVisiable: false
                        })
                    }}
                >
                    <RoleForm
                        wrappedComponentRef={(form) => {
                            this.roleForm = form
                        }}
                    />
                </Modal>
                <Modal
                    visible={this.state.isPermissionVisiable}
                    title={"权限设置"}
                    width={600}
                    onOk={this.handlePermissionSubmit}
                    onCancel={() => {
                        this.permForm.props.form.resetFields();
                        this.setState({
                            isPermissionVisiable: false
                        })
                    }}
                >
                    <PermEditForm
                        roleInfo={this.state.roleInfo}
                        wrappedComponentRef={(form) => {
                            this.permForm = form
                        }}
                        menuInfo={this.state.menuInfo}
                        patchMenuInfo={(checkedKeys) => {
                            this.setState({
                                menuInfo:checkedKeys
                            })
                        }}
                    />
                </Modal>
            </div>
        )
    }
}


class RoleForm extends React.Component {

    render() {
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 19}
        }
        const {getFieldDecorator} = this.props.form

        const type = this.props.type
        const userInfo = this.props.userInfo || {}
        console.log(userInfo)
        return (
            <Form layout='horizontal' {...formItemLayout}>
                <FormItem label='角色名'>
                    {
                        getFieldDecorator('role_name')(
                            <Input/>
                        )
                    }
                </FormItem>
                <FormItem label='状态'>
                    {
                        getFieldDecorator('role_status', {
                            initialValue: userInfo.status,
                            placeholder: '请选择状态'
                        })(
                            <Select>
                                <Option value={1}>开启</Option>
                                <Option value={0}>关闭</Option>
                            </Select>
                        )
                    }
                </FormItem>
            </Form>
        )
    }
}

RoleForm = Form.create({})(RoleForm)


class PermEditForm extends React.Component{
    renderTreeNodes = (data) => {
        return data.map((item)=>{
            if(item.children){
                return <TreeNode title={item.title} key={item.key}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            } else {
                return <TreeNode title={item.title} key={item.key} />
            }
        })
    }

    onCheck = (checkedKeys)=>{
        this.props.patchMenuInfo(checkedKeys)
    }

    render() {
        const {getFieldDecorator} = this.props.form
        const formItemLayout = {
            labelCol: {span:5},
            wrapperCol: {span:19}
        }
        const roleInfo = this.props.roleInfo
        const menuInfo = this.props.menuInfo
        return (
            <Form layout={'horizontal'} {...formItemLayout}>
                <FormItem label={'角色名'}>
                    <Input disabled placeholder={roleInfo.role_name}/>
                </FormItem>
                <FormItem label='状态'>
                    {
                        getFieldDecorator('role_status', {
                            initialValue: roleInfo.status,
                        })(
                            <Select>
                                <Option value={1}>开启</Option>
                                <Option value={0}>关闭</Option>
                            </Select>
                        )
                    }
                </FormItem>
                <Tree
                    checkable
                    defaultExpandAll
                    onCheck={(checkedKeys)=>{
                        this.onCheck(checkedKeys)
                    }}
                    checkedKeys={menuInfo}
                >
                    <TreeNode title="平台权限" key="platform_all">
                        {this.renderTreeNodes(menuData)}
                    </TreeNode>
                </Tree>
            </Form>
        )
    }
}
PermEditForm = Form.create({})(PermEditForm)

